package com.jluzh10.learning.web.controller;

import com.jluzh10.learning.domain.PictureCarousel;
import com.jluzh10.learning.service.PictureCarouselService;
import com.jluzh10.learning.utils.ResponseData;
import com.jluzh10.learning.utils.UploadUtil;
import com.jluzh10.learning.utils.qiniu.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author yzg
 * @create 2019/5/26
 *
 * 轮播图控制器
 */
@Controller
@RequestMapping("/carousel")
public class PictureCarouselController {
    private final PictureCarouselService carouselService;

    @Autowired
    public PictureCarouselController(PictureCarouselService carouselService) {
        this.carouselService = carouselService;
    }


    /**
     * 上传一张轮播图
     * @param carousel 轮播图对象
     * @param file  图片文件
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "add",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData add(PictureCarousel carousel,@Valid MultipartFile file) throws IOException {

        //上传轮播图到七牛云返回key
        if (!file.isEmpty()){
            String s = QiniuUtil.uploadFile(file.getInputStream(),
                    UploadUtil.generateRandonFileName(Objects.requireNonNull(file.getOriginalFilename())));
            //储存封面key
            carousel.setPicture(s);
        }
        carouselService.add(carousel);
        return new ResponseData().success();
    }

    /**
     * 查询轮播图
     * @param size 查询数量
     * @return
     */
    @RequestMapping(value = "",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData find(Integer size){
        if (size==null){
            size=0;
        }
        //获取指定数量的轮播图
        List<PictureCarousel> carousels = carouselService.findByNum(size);
        //获取轮播图地址
        for (PictureCarousel carousel:carousels){
            carousel.setPicture(QiniuUtil.getUrlByCarousel(carousel.getPicture()));
        }

        return new ResponseData().success().data(carousels);
    }

}
